from selenium import selenium
import urllib
import re
import json
import restaurantQuery
import time
import videoQuery

driver = "hello"
#Open up gmail
gmailInboxStr = "https://mail.google.com/mail/?shva=1#inbox"
gmailPage = "https://mail.google.com"
yelpPage = "http://yelp.com"
inboxPart = "/mail/?shva=1#inbox"

googlePage = "http://google.com"
googleMapsPage = "http://maps.google.com" 
youtubePage = "http://youtube.com"

rickRollVideo = "http://www.youtube.com/watch?v=oHg5SJYRHA0"

mapsPlaces = ["Old Town State Historic Park", "Balboa Park", "House of Blues"]
mapsBeach = "http://maps.google.com/maps?q=" + "La Jolla to "

mapsIndex = 0

mailNums = []

matchSite = "http://match.com"


#mapsSite = "http://maps.google.com/maps?q=beach"

stackOverFlow = "http://stackoverflow.com/search?q=i+have+a+question"

#YGL queries
#Find info based on current city
#select * from geo.places where text="la jolla, san diego"

def openHomePage():
    global driver
    driver = selenium("localhost", 4444, "*firefox C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe", googlePage)
    driver.start()
    driver.window_maximize()
    driver.open("/")
    time.sleep(3)
    
def openSite(websiteName=googlePage):
    driver.open(websiteName)

def queryGoogle(name):
    driver.open(googlePage + "#q=" + name)

zipCode = "92122"
city = "La Jolla"
state = "CA"

cityNState = city + "," + state 
    
u1 = """http://query.yahooapis.com/v1/public/yql?q=select * from upcoming.venue where search_text="jazz" and location="la jolla, san diego, ca"&format=json"""

query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20upcoming.venue%20where%20search_text%3D%22jazz%22%20and%20location%3D%22la%20jolla%2C%20san%20diego%2C%20ca%22&format=json&diagnostics=true&callback="

#select * from geo.placefinder where text="3415 lebon drive, la jolla, san diego, ca"
myLocationQuery = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text%3D%22" + cityNState + "%22&format=json&diagnostics=true&callback="
#myLocationQuery = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text%3D%223415%20lebon%20drive%2C%20la%20jolla%2C%20san%20diego%2C%20ca%22&format=json&diagnostics=true&callback="


#myWeatherQuery = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%3D"+zipCode+"&format=json&diagnostics=true&callback="


#Just get the codes for the weather
myWeatherQuery = "http://query.yahooapis.com/v1/public/yql?q=select%20item.forecast.code%20from%20weather.forecast%20where%20location%3D90210&format=json&diagnostics=true&callback="

def getLocationData():
    jsonDataStr = urllib.urlopen(myLocationQuery).readlines()[0] #returns a string with all the json data
    res = json.loads(jsonDataStr) #resulting json dictionary
    
    lat =  res['query']['results']['Result']['latitude']
    long = res['query']['results']['Result']['longitude']
    zipCode = res['query']['results']['Result']['uzip']
    city = res['query']['results']['Result']['city']
    
    print(zipCode)
    
    lat = 32.866584
    long = -117.224672
    zipCode = 92122
    city = "San Diego"
    
def getWeatherData():
    
    jsonDataStr = urllib.urlopen(myWeatherQuery).readlines()[0]
    res = json.loads(jsonDataStr)
   
    todayCode = int(res['query']['results']['channel'][0]['item']['forecast']['code'])

    weatherList = ["inside", "coldOutsideSmokyWindy", "niceNight", "niceDay", "hot", "rain"]
    
    condition = ""
    if(todayCode <= 19):
        condition = weatherList[0]
    elif(todayCode <= 26):
        condition = weatherList[1] #smoky windy
    elif(todayCode == 27 or todayCode == 29 or todayCode == 31 or todayCode == 33):
        condition = weatherList[2] #nice night
    elif(todayCode == 28 or todayCode == 30 or todayCode == 32 or todayCode == 34 or todayCode == 44):
        condition = weatherList[3] #nice day
    elif(todayCode == 36):
        condition = weatherList[4] #hot
    else:
        condition = weatherList[5] #raining
    
    print(condition)
    
#select * from weather.forecast where location=90210

level = 1
#No == left arm shaking == shake hand == open
#Right arm up == Reply == rolling camera

statesL = ['armsUpX', 'basket', 'bending', 'bendOver', 'boogieNights', 'confusion', 'cross', 'lickStamp', 'open', 'reply']

previousAction = "something"

#Used for when we are already at level 2 and we need to know what we just did for level 2
previousItemLevel2 = "fast food"

#Need a state machine that based on the state we are in sends us to the right command 

runOnce = True
runOnceBasket = True

def doAction(a):
    """
    @param a is the action as a string that we want to perform
    """
    global level, previousAction, zipCode, previousItemLevel2, mapsIndex, mapsPlaces
    global runOnce, runOnceBasket
    
    if(level == 1):
        #User is hungry
        if(a == 'bending'):
            #open yelp
            if(runOnce):
                openSite(yelpPage)
                runOnce = False
                level = 2
                previousAction = a
        elif (a == 'confusion' or a == 'armsUpX'):
            #open google maps with a suggestion
            openSite(mapsBeach + mapsPlaces[mapsIndex])
            mapsIndex += 1
            mapsIndex %= len(mapsPlaces)
            level = 2
            previousAction = a    
        elif (a == 'reply' or a == 'basket'):
            openSite(youtubePage)
            level = 2
            previousAction = a
    else: #level is 2
        
        #Go back to homepage
        if (a == 'armsUpX' or a == 'confusion'):
            level = 1
            openSite(googlePage)
        
        #User was hungry    
        if(previousAction == 'bending'):
            if(a == 'boogieNights'):
                #Do italian yelp search
                url = restaurantQuery.findRestaurantsByLocationAndType(zipCode, 'italian')
                previousItemLevel2 = 'italian'
                openSite(url)
            elif(a == 'lickStamp'):
                #Go to a bar
                url = restaurantQuery.findRestaurantsByLocationAndType(zipCode, 'bars')
                previousItemLevel2 = 'bars'
                openSite(url)
            elif(a == 'open'): #open means no
                #Do next yelp search
                url = restaurantQuery.findRestaurantsByLocationAndType(zipCode, previousItemLevel2)
                openSite(url)
                    
        elif(previousAction == 'confusion'):    
            if(a == 'open'):
                #Do next map search
                 openSite(mapsBeach + mapsPlaces[mapsIndex])
                 mapsIndex += 1
                 mapsIndex %= len(mapsPlaces) 
                
        elif(previousAction == 'reply'):
            if(a == 'reply'):
                url = videoQuery.findVideo("workout+video")
                previousItemLevel2 = "workout+video"
                openSite(url)
            elif(a == 'basket'):
                if(runOnceBasket):
                    url = videoQuery.findVideo("nba+highlights")
                    previousItemLevel2 = "nba+highlights"
                    openSite(url)
                    runOnceBasket = False
            elif(a == 'open'):
                #Do next youtube search
                url = videoQuery.findVideo(previousItemLevel2)
                openSite(url) 
            elif(a == 'boogieNights'):
                openSite(rickRollVideo) #TODO change
            

def runGmail():
    """
    Open up a new browser window with firefox and open gmail
    """
    #Get an instance of firefox
    global driver
    driver = selenium("localhost", 4444, "*firefox C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe", gmailPage)
    driver.start()
    driver.window_maximize()
    driver.open("/")
    
def userLoggedIn():
    """
    Once user has logged in run this once
    """
    global mailNums, driver
    driver.refresh()
    #driver.open(inboxPart)
    mailNums = listOfMailNumbers()
    
def openMail(num):
    """
        Defines which mail we want to open
    """
    global mailNums, driver 

    mailStr = inboxPart + "/" + mailNums[num]
    driver.open(mailStr)

def backToInbox():
    """
    Sends the user back to their inbox
    """
    global driver
    driver.get(gmailInboxStr)

def listOfMailNumbers():
    global driver
    finalList = []

    source = driver.get_html_source()
    strSource = source.encode('ascii', 'ignore')
    
    #Starting from var VIEW_DATA until the end of the string
    smallerSource = strSource[strSource.find("var VIEW_DATA="):]
 
    #For getting just where gmail has sets of 3 numbers
    matchString = ",[\"[a-zA-Z0-9]+\",\"[a-zA-Z0-9]+\",\"[a-zA-Z0-9]+\""
    group3numList = re.findall(matchString, smallerSource)
    
    #For getting these numbers from the group of three
    #One element in group3numList is ,["0asdf322dsf","3099adsfdsa","0234234"]
    #So for each of those items, we want to extract just one number
    matchStr2 = "[a-zA-Z0-9]+"

    
    for group3num in group3numList:
        numList = re.findall(matchStr2, group3num)
        #numList has the 3 numbers we want, the first 
        #definitely being a menu for the gmail page
        finalList.append(numList[0])

    return finalList

if __name__ == '__main__':
    """
    Use case
    
    runGmail()
    #Wait until user logs in
    userLoggedIn()
    openMail(1)
    openMail(10)
    backToInbox()
    """
    print ("hi")